<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/12
 * Time: 8:46
 */

namespace app\common\model;


use think\Model;
use app\common\validate\Auth as AuthValidate;
use think\Validate;

class Auth extends Model
{
    protected $autoWriteTimestamp = true;

    protected static function init(){
        self::event('after_insert',function($auth){
            //默认是最顶级的auth_ids
            $auth_ids = $auth['id'];
            //若传过来的auth_ids不为空,进行拼接
            if(!empty($auth['auth_ids'])){
                $auth_ids = $auth['auth_ids'].','.$auth['id'];
            }
            //获取auth_ids中逗号的个数
            $level = substr_count($auth_ids,',');
            //更新
            $res = db('auth')
                ->where('id','=',$auth['id'])
                ->update([
                    'auth_ids' => $auth_ids,
                    'level' => $level
                ]);
        });

        self::event('before_update',function($auth){
//            implode(',',[1,2,3]); 将数组转成字符串
            $arr = explode('||',$auth['pid']);
            $auth['pid'] = $arr[0];
            $auth['auth_ids'] = $auth['id'];
            if(!empty($arr[1])){
                $auth['auth_ids'] = $arr[1].','.$auth['id'];
            }
            $auth['level'] = substr_count($auth['auth_ids'],',');
        });
    }

    public function addData(){
        $dt = input('post.');
        //验证
        $validate = new AuthValidate();
        if(!$validate->scene('add')->check($dt)){
            return $validate->getError();
        }

        //处理一下pid

        $arr = explode('||',$dt['pid']);
        $dt['pid'] = $arr[0];
        $dt['auth_ids'] = $arr[1];

        //添加数据
        $res = $this->allowField(true)->save($dt);

        if(!$res){
            return '添加失败';
        }

        return true;
    }

    public function sel(){
        $where = [];
        /***********权限名称************/
        $auth_name = input('auth_name');
        if($auth_name){
            $where['auth_name'] = ['=',$auth_name];
        }
        $data = $this
            ->where($where)
            ->order('auth_ids')
            ->paginate(15);
        return $data;
    }

    public function editData(){
        $dt = input('post.');

        //验证
        $validate = new AuthValidate();
        if(!$validate->scene('edit')->check($dt)){
            return $validate->getError();
        }


        //更新数据
        $res = $this->allowField(true)->save($dt,['id'=>$dt['id']]);
        if(!$res){
            return '更新失败';
        }
        return true;
    }
}